package com.example.community.service;

import com.example.community.entity.LoginTicket;
import com.example.community.entity.User;
import com.example.community.mapper.LoginTicketMapper;
import com.example.community.mapper.UserMapper;
import com.example.community.util.CommunityConstant;
import com.example.community.util.CommunityUitl;
import com.example.community.util.MailClient;
import com.example.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService implements CommunityConstant {
    @Autowired
    private UserMapper userMapper;

//    @Autowired
//    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    // 注册
    public Map<String, Object> register(User user){
        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if(user == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }

        // 验证账号
        User u = userMapper.selectByName(user.getUsername());
        if( u != null){
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }
        // 验证邮箱
        u = userMapper.selectByEmail(user.getEmail());
        if( u != null){
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }
        // 注册用户
        user.setSalt(CommunityUitl.generateUUID().substring(0,5));  // 生成随机字符串作为密码加盐
        user.setPassword(CommunityUitl.md5(user.getPassword() + user.getSalt()));   // 密码用md5加密
        user.setType(0);
        user.setStatus(0); // 未激活
        user.setActivationCode(CommunityUitl.generateUUID()); // 激活码
        user.setHeaderUrl(String.format("http://images.nowcoder.com.head/%dt.png",new Random().nextInt(1000)));     // 头像
        user.setCreateTime(new Date()); // 创建日期
        userMapper.insertUser(user);

        // 激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());

        // u = userMapper.selectByName(user.getUsername());        // 获取用户的自增id
        // String url = "http://localhost:8080" + "/community" + "/activation/" + u.getId() + "/" + u.getActivationCode();
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);

        return map;

    }

    // 激活
    public int activation(int userId, String code){
        User user = userMapper.selectById(userId);
        if(user.getStatus() == 1){
            return ACTIVATION_REPEAT;  // 重复激活
        }else if(user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId, 1);
            clearCache(userId); // 清理缓存
            return ACTIVATION_SUCCESS;  // 激活成功
        }else{
            return ACTIVATION_FAILURE;  // 激活失败
        }
    }


    // 登录
    public Map<String, Object> login(String username, String password, int expiredSeconds){
        Map<String, Object> map = new HashMap<>();

        // 空值处理
        if(StringUtils.isBlank(username)){
            map.put("username", "账号不能为空");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("password", "密码不能为空");
            return map;
        }

        // 验证账号 因为账号的唯一性，所以不需要，而且密码的加密的，所以密码验证需要另外进行
        User user = userMapper.selectByName(username);
        if(user == null){
            map.put("usernameMsg", "该账号不存在！");
            return map;
        }
        if(user.getStatus() == 0){
            map.put("usernameMsg", "该账号未激活！");
            return map;
        }

        // 验证密码
        password = CommunityUitl.md5(password + user.getSalt());
        if(!user.getPassword().equals(password)){
            map.put("passwordMsg", "密码不正确!");
            return map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUitl.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        // loginTicketMapper.insertLoginTicket(loginTicket);

        // 保存到redis中
        String ticketKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(ticketKey, loginTicket);

        map.put("ticket", loginTicket.getTicket());

        return map;

    }

    // 退出登录
    public void logout(String ticket){
         // loginTicketMapper.updateStatus(ticket, 1);
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        // 先取出数据
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
        loginTicket.setStatus(1);   // 改变凭证的状态
        // 重新保存在redis中
        redisTemplate.opsForValue().set(ticketKey, loginTicket);


    }

    // 登录凭证
    public LoginTicket findLoginTicket(String ticket){
        // return loginTicketMapper.selectByTicket(ticket);
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
    }
    // 更新用户头像
    public int updateHeader(int userId, String headerUrl){
        int i = userMapper.updateHeader(userId, headerUrl);
        clearCache(userId); // 清理缓存
        return i;
    }

    //修改密码
    public Map<String, Object> updatePassword(int userId, String oldPassword, String newPassword, String confirmPassword){
        Map<String, Object> map = new HashMap<>();
        if(StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword) || StringUtils.isBlank(confirmPassword)){
            map.put("errorPsd", "密码不能为空!");
            return map;
        }
        if(!newPassword.equals(confirmPassword)){
            map.put("errorPsd","两次密码输入不一致！");
            return map;
        }
        User user = userMapper.selectById(userId);
        oldPassword = CommunityUitl.md5(oldPassword + user.getSalt());
        if(!user.getPassword().equals(oldPassword)){
            map.put("errorPsd","原密码输入错误！");
            return map;
        }
        user.setSalt(CommunityUitl.generateUUID().substring(0,5));
        confirmPassword = CommunityUitl.md5(confirmPassword + user.getSalt());
        userMapper.updatePassword(userId, confirmPassword, user.getSalt());

        map.put("successPsd","修改成功");

       return map;

    }

    public User findUserByName(String username){
        return userMapper.selectByName(username);
    }

    // 获取用户信息
    public User findUserById(int id){
        // return userMapper.selectById(id);
        // 向去缓存查找
        User user = getUserByCache(id);
        if(user == null){
            user = initCacha(id);
        }
        return user;
    }

    // 1.优先从redis缓存中取值
    private User getUserByCache(int userId){
        String userKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(userKey);
    }
    // 2.取不到时，初始化redis缓存数据
    private User initCacha(int userId){
        // 从数据库中查数据
        User user = userMapper.selectById(userId);
        String userKey = RedisKeyUtil.getUserKey(userId);
        // 加入到redis缓存中，并设置过时时间
        redisTemplate.opsForValue().set(userKey, user, 10, TimeUnit.MINUTES);
        return user;
    }
    // 3. 数据变更时，清除缓存数据
    private void clearCache(int userId){
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(userKey);
    }

    public Collection<? extends GrantedAuthority> getAuthorities(int userId){
        User user = this.findUserById(userId);

        List<GrantedAuthority> list = new ArrayList<>();
        // 赋予权限
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()){
                    case 1:
                        return AUTHORITY_ADMIN;   // 管理员
                    case 2:
                        return AUTHORITY_MODERATOR;  // 版主
                    default:
                        return AUTHORITY_USER;  // 普通用户
                }
            }
        });
        return list;
    }


}

